package com.sk.weichat.ui.account;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageLogin;
import com.sk.weichat.bean.Code;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DestroyActivityUtil;
import com.sk.weichat.util.EventBusHelper;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

/**
 * 绑定手机/更换手机
 * create by SWY
 */
public class BandAndChangePhoneActivity extends BaseActivity implements View.OnClickListener{

    private TextView tvPrefix;
    private EditText etPhoneNum;
    private ImageView ivClear;
    private Button btnSend;
    String openId,type;

    private int mobilePrefix = 86;
    private String loginType;

    public BandAndChangePhoneActivity() {
        noLoginRequired();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//暗色主题状态栏(白字)
            this.getWindow().getDecorView()
                    .setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_VISIBLE);
        }
        setContentView(R.layout.activity_phone_change);
        openId = getIntent().getStringExtra("openId");
        type = getIntent().getStringExtra("type");//0不校验手机号，1是校验手机号是否存在，2手机是否已被注册
        loginType = getIntent().getStringExtra("loginType");//2 QQ登录 3微信登录

        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(Color.parseColor("#00000000"));

        tvPrefix = findViewById(R.id.tv_prefix_phone);
        tvPrefix.setOnClickListener(this);
        etPhoneNum = findViewById(R.id.phone_num_phone);
        ivClear = findViewById(R.id.iv_clear_phone);
        ivClear.setOnClickListener(this);
        btnSend = findViewById(R.id.btn_send_phone);
        btnSend.setOnClickListener(this);
        ImageView ivBack = findViewById(R.id.iv_title_left);
        TextView tvTitle = findViewById(R.id.tv_phone_title);
        String from=getIntent().getStringExtra("from");
        if(from!=null&&from.equals("change")){
            tvTitle.setText("更换手机号");
        }
        ivBack.setImageResource(R.mipmap.ic_back_white);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DestroyActivityUtil.destoryActivity("BandAndChangePhoneActivity");
                finish();
            }
        });
        chinaNumInput();
        permissionRequest();
        EventBusHelper.register(this);
        DestroyActivityUtil.addDestoryActivityToMap(BandAndChangePhoneActivity.this, "BandAndChangePhoneActivity");
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(MessageLogin message) {
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_prefix_phone:// 选择国家区号
                Intent intent = new Intent(BandAndChangePhoneActivity.this, SelectPrefixActivity.class);
                startActivityForResult(intent, SelectPrefixActivity.REQUEST_MOBILE_PREFIX_LOGIN);
                break;
            case R.id.iv_clear_phone:
                etPhoneNum.setText("");
                break;
            case R.id.btn_send_phone:
                requestAuthCode();
                break;
        }
    }

    private void goToCode() {
        String str = etPhoneNum.getText().toString();
        if (TextUtils.isEmpty(str)) {
            ToastUtil.showToast(mContext, getString(R.string.please_input_phone_number));
            return;
        }
        if (mobilePrefix == 86) {
            if (str.length() != 13 || !str.startsWith("1")) {
                ToastUtil.showToast(mContext, "请输入正确的中国大陆区域手机号码");
                return;
            }
        }
        Intent intent = new Intent(this, SMSCodeActivity.class);
        intent.putExtra("phoneNum", str);
        intent.putExtra("areaCode", mobilePrefix + "");
        String from = getIntent().getStringExtra("from");
        intent.putExtra("isLogin", from!=null&&from.equals("change")?"2":"1");
        intent.putExtra("openId",openId);
        intent.putExtra("type",type);
        intent.putExtra("loginType",loginType);
        intent.putExtra("nickname", getIntent().getStringExtra("nickname"));
        intent.putExtra("sex",  getIntent().getStringExtra("sex"));
        intent.putExtra("imgurl", getIntent().getStringExtra("imgurl"));
        startActivity(intent);
    }

    //请求短信读取权限
    private void permissionRequest() {
        boolean isReadContacts = PermissionUtil.checkSelfPermissions(this,
                new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS});
        if (!isReadContacts) {
            PermissionUtil.requestPermissions(this, 0x02,
                    new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS});
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != SelectPrefixActivity.RESULT_MOBILE_PREFIX_SUCCESS)
            return;
        mobilePrefix = data.getIntExtra(Constants.MOBILE_PREFIX, 86);
        tvPrefix.setText("+" + mobilePrefix);
        etPhoneNum.setText("");
        if (mobilePrefix == 86) {
            etPhoneNum.setFilters(new InputFilter[]{new InputFilter.LengthFilter(13)});
        }else {
            etPhoneNum.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        }
    }

    //输入号码格式监听
    private void chinaNumInput() {
        String inputStr = etPhoneNum.getText().toString();
        if (TextUtils.isEmpty(inputStr)){
            ivClear.setVisibility(View.INVISIBLE);
            btnSend.setTextColor(mContext.getResources().getColor(R.color.white));
            btnSend.setBackgroundResource(R.drawable.bg_round_white_35);
        }else {
            ivClear.setVisibility(View.VISIBLE);
            btnSend.setTextColor(mContext.getResources().getColor(R.color.deep_purple));
            btnSend.setBackgroundResource(R.drawable.bg_round_white);
        }
        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    ivClear.setVisibility(View.INVISIBLE);
                    btnSend.setTextColor(mContext.getResources().getColor(R.color.white));
                    btnSend.setBackgroundResource(R.drawable.bg_round_white_35);
                    return;
                }
                ivClear.setVisibility(View.VISIBLE);

                StringBuilder sb = new StringBuilder(s.toString());
                if (mobilePrefix == 86) {//中国大陆号码时，号码 *** **** ****格式化
                    if (s.length() == 13){
                        btnSend.setTextColor(mContext.getResources().getColor(R.color.deep_purple));
                        btnSend.setBackgroundResource(R.drawable.bg_round_white);
                    }else {
                        btnSend.setTextColor(mContext.getResources().getColor(R.color.white));
                        btnSend.setBackgroundResource(R.drawable.bg_round_white_35);
                    }
                    if (before == 0) { //上一次是add时
                        if (sb.length() == 3 || sb.length() == 8) {//自动追加空格
                            sb.append(' ');
                        }
                    }
                    if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                        sb.insert(sb.length() - 1, ' ');
                    }
                }else{
                    btnSend.setTextColor(mContext.getResources().getColor(R.color.deep_purple));
                    btnSend.setBackgroundResource(R.drawable.bg_round_white);
                }
                if (!sb.toString().equals(s.toString())) {
                    etPhoneNum.setText(sb.toString());
                    etPhoneNum.setSelection(sb.toString().length());
                }

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    /**
     * 请求验证码
     */
    private void requestAuthCode() {
        Map<String, String> params = new HashMap<>();
        String language = Locale.getDefault().getLanguage();
        params.put("language", language);
        params.put("areaCode", mobilePrefix+"");
        params.put("telephone", etPhoneNum.getText().toString().replace(" ", ""));
        params.put("openId", openId);
        params.put("type", type);
        DialogHelper.showMessageProgressDialog(this, "正在请求验证码...");
        HttpUtils.get().url(coreManager.getConfig().SEND_LOGIN_CODE)
                .params(params)
                .build()
                .execute(new BaseCallback<Code>(Code.class) {

                    @Override
                    public void onResponse(ObjectResult<Code> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
//                            ToastUtil.showToast(mContext, getString(R.string.verification_code_send_success));
                            goToCode();
                        } else {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? "验证码获取失败" : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            DestroyActivityUtil.destoryActivity("BandAndChangePhoneActivity");
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
